import { ApiProperty, IntersectionType, PartialType } from '@nestjs/swagger'
import { Type } from 'class-transformer'
import {
  ArrayMaxSize,
  ArrayMinSize,
  ArrayNotEmpty,
  IsEmail,
  IsIn,
  IsInt,
  IsOptional,
  IsString,
  Matches,
  MaxLength,
  Min,
  MinLength,
  ValidateIf,
} from 'class-validator'
import { isEmpty } from 'lodash'

import { PagerDto } from '~/common/dto/pager.dto'

export class UserSaveDto {
  @ApiProperty({ description: '用户ID' })
  @IsInt()
  @Min(0)
  @IsOptional()
  id?: number

  @ApiProperty({ description: '用户账号', example: 'admin' })
  @IsString()
  @Matches(/^[\s\S]+$/)
  @MinLength(4)
  @MaxLength(20)
  username: string

  @ApiProperty({ description: '登录密码', example: 'a123456' })
  @IsOptional()
  @Matches(/^\S*(?=\S{6})(?=\S*\d)(?=\S*[A-Z])\S*$/i, {
    message: '密码必须包含数字、字母，长度为6-16',
  })
  password?: string

  @ApiProperty({ description: '用户昵称', example: 'admin' })
  @IsString()
  @MinLength(1)
  @MaxLength(30)
  nickname: string

  @ApiProperty({ description: '备注' })
  @IsOptional()
  @IsString()
  @MaxLength(500)
  remark?: string

  @ApiProperty({ description: '部门ID', type: Number })
  @Type(() => Number)
  @IsInt()
  @IsOptional()
  deptId?: number

  @ApiProperty({ description: '岗位编号数组' })
  @IsOptional()
  @IsString()
  @MaxLength(255)
  postIds?: string

  @ApiProperty({ description: '用户邮箱', example: 'bqy.dev@qq.com' })
  @IsEmail()
  @ValidateIf(o => !isEmpty(o.email))
  @IsOptional()
  @MaxLength(50)
  email?: string

  @ApiProperty({ description: '手机号码' })
  @IsOptional()
  @IsString()
  @Matches(/^1[3-9]\d{9}$/, { message: '请输入正确的手机号码' })
  mobile?: string

  @ApiProperty({ description: '用户性别（0未知 1男 2女）' })
  @IsIn([0, 1, 2])
  @IsOptional()
  sex?: number

  @ApiProperty({ description: '头像地址' })
  @IsOptional()
  @IsString()
  @MaxLength(512)
  avatar?: string

  @ApiProperty({ description: '帐号状态（0正常 1停用）' })
  @IsIn([0, 1])
  @IsOptional()
  status?: number

  @ApiProperty({ description: '归属角色', type: [Number] })
  @ArrayNotEmpty()
  @ArrayMinSize(1)
  @ArrayMaxSize(3)
  @IsOptional()
  roleIds?: number[]
}

export class UserQueryDto extends IntersectionType(PagerDto, PartialType(UserSaveDto)) {}
